package com.sky.youxue.service;

import com.sky.youxue.common.enums.ExceptionEnum;
import com.sky.youxue.common.exception.youxueException;
import com.sky.youxue.mapper.SpecGroupMapper;
import com.sky.youxue.mapper.SpecParamMapper;
import com.sky.youxue.mapper.SpecificationsMapper;
import com.sky.youxue.production.pojo.SpecGroup;
import com.sky.youxue.production.pojo.SpecParam;
import com.sky.youxue.production.pojo.Specification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class SpecificationService {

    @Autowired
    private SpecificationsMapper specificationsMapper;
    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private SpecParamMapper specParamMapper;

    public List<SpecGroup> queryGroupByCid(Long cid) {
        SpecGroup group = new SpecGroup();
        group.setCid(cid);
        List<SpecGroup> list = specGroupMapper.select(group);
        if (CollectionUtils.isEmpty(list)) {
            throw new youxueException(ExceptionEnum.SPEC_GROUP_NOT_FOUND);
        }
        return list;
    }
    public List<SpecGroup> querySpecsByCid(Long cid) {
        // 查询规格组
        List<SpecGroup> groups = this.queryGroupByCid(cid);
        if (CollectionUtils.isEmpty(groups)) {
            throw new youxueException(ExceptionEnum.SPEC_GROUP_NOT_FOUND);
        }
        SpecParam param = new SpecParam();
        groups.forEach(g -> {
            // 查询组内参数
            g.setParams(this.querySpecParams(g.getId(), null, null, null));
        });
        return groups;
    }

    public List<SpecParam> querySpecParams(Long gid, Long cid, Boolean searching, Boolean generic) {
        SpecParam specParam = new SpecParam();
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setSearching(searching);
        specParam.setGeneric(generic);
        List<SpecParam> list = specParamMapper.select(specParam);
        if (CollectionUtils.isEmpty(list)) {
            throw new youxueException(ExceptionEnum.SPEC_PARAM_NOT_FOUND);
        }
        return list;
    }



    /**
     * 查询分类规格模版的方法
     * @param id
     * @return
     */
    public String querySpecifications(Long id) {

        Specification specification = specificationsMapper.selectByPrimaryKey(id);
        if (specification==null){
            return null;
        }
        String specifications = specification.getSpecifications();
        return specifications;
    }

    /**
     * 添加模版的方法
     * @param specification
     */
    public void addSpecifications(Specification specification) {
        this.specificationsMapper.insert(specification);
    }

    /**
     * 修改模版的方法
     * @param specification
     */
    public void updateSpecifications(Specification specification) {
        this.specificationsMapper.updateByPrimaryKey(specification);
    }


}
